﻿using System;
using System.Deployment.Application;
using System.Windows.Forms;
using SmartWallpaperChanger.Properties;

namespace SmartWallpaperChanger
{
    public class Updater : IDisposable
    {
        private Timer timer;

        public static string Version
        {
            get
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    Version version = ApplicationDeployment.CurrentDeployment.CurrentVersion;
                    return version.ToString();
                }
                
                return string.Empty;
            }
        }

        public static bool IsUpdateAvailable
        {
            get
            {
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    return ApplicationDeployment.CurrentDeployment.CheckForUpdate();
                }
                
                return false;
            }
        }

        public event EventHandler UpdateAvailable;

        public static void Update()
        {
            ApplicationDeployment.CurrentDeployment.Update();
            Application.Restart();
        }

        public Updater()
        {
            if(IsUpdateAvailable) Update();
        }

        public void StartPeriodicChecking()
        {
            timer = new Timer();
            timer.Interval = DaysToMilliseconds();
            timer.Tick += delegate { if (UpdateAvailable != null) UpdateAvailable(this, new EventArgs()); };
            timer.Start();
        }

        private int DaysToMilliseconds()
        {
            return Settings.Default.UpdateInterval*24*60*60*1000;
        }

        public void StopPeriodicChecking()
        {
            timer.Stop();
        }

        public void Dispose()
        {
            StopPeriodicChecking();
            timer.Dispose();
        }
    }
}
